use bytes::{BufMut, BytesMut};
use serde::{
    ser::{
        self, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple,
        SerializeTupleStruct, SerializeTupleVariant,
    },
    Serialize, Serializer,
};

use crate::{
    error::RedisError,
    resp::{
        ERROR_FAKE_FIELD, PUSH_FAKE_FIELD, SET_FAKE_FIELD, TAG_ARRAY, TAG_BIG_NUMBER,
        TAG_BULK_STRING, TAG_DOUBLE, TAG_INTEGER, TAG_MAP, TAG_PUSHES, TAG_SET, TAG_SIMPLE_ERROR,
        TAG_SIMPLE_STRING,
    },
};

pub struct Resp3Serializer {
    is_error: bool,
    output: BytesMut,
}

impl Resp3Serializer {
    pub fn new() -> Self {
        Resp3Serializer {
            is_error: false,
            output: BytesMut::new(),
        }
    }

    fn serialize_common<T: ToString>(&mut self, tag: u8, val: T) {
        self.output.put_u8(tag);
        self.output.put_slice(val.to_string().as_bytes());
    }
}

impl<'a> Serializer for &'a mut Resp3Serializer {
    type Ok = ();

    type Error = RedisError;

    type SerializeSeq = Self;

    type SerializeTuple = Self;

    type SerializeTupleStruct = Self;

    type SerializeTupleVariant = Self;

    type SerializeMap = Self;

    type SerializeStruct = Self;

    type SerializeStructVariant = Self;

    fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
        self.output.put_slice(if v { b"#t\r\n" } else { b"#f\r\n" });
        Ok(())
    }

    fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
        self.serialize_common(TAG_INTEGER, v);
        Ok(())
    }

    fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
        self.serialize_common(TAG_INTEGER, v);
        Ok(())
    }

    fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
        self.serialize_common(TAG_INTEGER, v);
        Ok(())
    }

    fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
        self.serialize_common(TAG_INTEGER, v);
        Ok(())
    }

    fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
        self.serialize_common(TAG_INTEGER, v);
        Ok(())
    }

    fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
        self.serialize_common(TAG_INTEGER, v);
        Ok(())
    }

    fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
        self.serialize_common(TAG_INTEGER, v);
        Ok(())
    }

    fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
        self.serialize_common(TAG_INTEGER, v);
        Ok(())
    }

    fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
        self.serialize_common(TAG_DOUBLE, v);
        Ok(())
    }

    fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
        self.serialize_common(TAG_DOUBLE, v);
        Ok(())
    }

    fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
        let mut buf = [0; 4];
        _ = v.encode_utf8(&mut buf);
        if self.is_error {
            self.is_error = false;
            self.output.put_u8(TAG_SIMPLE_ERROR);
        } else {
            self.output.put_u8(TAG_SIMPLE_STRING);
        }
        self.output.put_slice(&buf);
        self.output.put_slice(b"\r\n");
        Ok(())
    }

    fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
        if self.is_error {
            self.is_error = false;
            self.output.put_u8(TAG_SIMPLE_ERROR);
        } else {
            self.output.put_u8(TAG_SIMPLE_STRING);
        }
        self.output.put_slice(v.as_bytes());
        self.output.put_slice(b"\r\n");
        Ok(())
    }

    fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
        self.output.put_u8(TAG_BULK_STRING);
        self.output.put_slice(v.len().to_string().as_bytes());
        self.output.put_slice(b"\r\n");
        self.output.put_slice(v);
        self.output.put_slice(b"\r\n");
        Ok(())
    }

    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
        self.serialize_unit()
    }

    fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
    where
        T: ?Sized + serde::Serialize,
    {
        value.serialize(self)
    }

    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
        self.output.put_slice(b"_\r\n");
        Ok(())
    }

    fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
        self.output.put_slice(b"_\r\n");
        Ok(())
    }

    fn serialize_unit_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str,
    ) -> Result<Self::Ok, Self::Error> {
        self.serialize_str(variant)
    }

    fn serialize_newtype_struct<T>(
        self,
        name: &'static str,
        value: &T,
    ) -> Result<Self::Ok, Self::Error>
    where
        T: ?Sized + serde::Serialize,
    {
        if name == ERROR_FAKE_FIELD {
            self.is_error = true;
        }
        value.serialize(self)
    }

    fn serialize_newtype_variant<T>(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        value: &T,
    ) -> Result<Self::Ok, Self::Error>
    where
        T: ?Sized + serde::Serialize,
    {
        self.output.put_u8(TAG_MAP);
        self.output.put_slice(b"1\r\n");
        variant.serialize(&mut *self)?;
        value.serialize(&mut *self)
    }

    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
        if let Some(len) = len {
            self.serialize_common(TAG_ARRAY, len);
            Ok(self)
        } else {
            Err(ser::Error::custom("the seq len is invalid"))
        }
    }

    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
        self.serialize_seq(Some(len))
    }

    fn serialize_tuple_struct(
        self,
        name: &'static str,
        len: usize,
    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
        match name {
            PUSH_FAKE_FIELD => {
                self.serialize_common(TAG_PUSHES, len);
                Ok(self)
            }
            SET_FAKE_FIELD => {
                self.serialize_common(TAG_SET, len);
                Ok(self)
            }
            _ => self.serialize_seq(Some(len)),
        }
    }

    fn serialize_tuple_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        len: usize,
    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
        self.output.put_u8(TAG_MAP);
        self.output.put_slice(b"1\r\n");
        variant.serialize(&mut *self)?;
        self.output.put_u8(TAG_ARRAY);
        self.serialize_common(TAG_INTEGER, len);
        Ok(self)
    }

    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
        if let Some(len) = len {
            self.serialize_common(TAG_MAP, len);
            Ok(self)
        } else {
            Err(ser::Error::custom("the map len is invalid"))
        }
    }

    fn serialize_struct(
        self,
        _name: &'static str,
        len: usize,
    ) -> Result<Self::SerializeStruct, Self::Error> {
        self.serialize_common(TAG_MAP, len);
        Ok(self)
    }

    fn serialize_struct_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        len: usize,
    ) -> Result<Self::SerializeStructVariant, Self::Error> {
        self.output.put_u8(TAG_MAP);
        self.output.put_slice(b"1\r\n");
        variant.serialize(&mut *self)?;
        self.serialize_common(TAG_MAP, len);
        Ok(self)
    }

    fn serialize_i128(self, v: i128) -> Result<Self::Ok, Self::Error> {
        self.serialize_common(TAG_BIG_NUMBER, v);
        Ok(())
    }

    fn serialize_u128(self, v: u128) -> Result<Self::Ok, Self::Error> {
        self.serialize_common(TAG_BIG_NUMBER, v);
        Ok(())
    }

    // fn collect_seq<I>(self, iter: I) -> Result<Self::Ok, Self::Error>
    // where
    //     I: IntoIterator,
    //     <I as IntoIterator>::Item: Serialize,
    // {
    //     let mut iter = std::iter.into_iter();

    //     let mut serializer = tri!(self.serialize_seq(iterator_len_hint(&iter)));
    //     tri!(iter.try_for_each(|item| serializer.serialize_element(&item)));
    //     serializer.end()
    // }

    // fn collect_map<K, V, I>(self, iter: I) -> Result<Self::Ok, Self::Error>
    // where
    //     K: Serialize,
    //     V: Serialize,
    //     I: IntoIterator<Item = (K, V)>,
    // {
    //     let mut iter = std::iter.into_iter();
    //     let mut serializer = tri!(self.serialize_map(iterator_len_hint(&iter)));
    //     tri!(iter.try_for_each(|(key, value)| serializer.serialize_entry(&key, &value)));
    //     serializer.end()
    // }

    // fn collect_str<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
    // where
    //     T: ?Sized + std::fmt::Display,
    // {
    //     self.serialize_str(&value.to_string())
    // }

    // fn is_human_readable(&self) -> bool {
    //     true
    // }
}

impl<'a> SerializeSeq for &'a mut Resp3Serializer {
    type Ok = ();

    type Error = RedisError;

    fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: ?Sized + serde::Serialize,
    {
        value.serialize(&mut **self)
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        Ok(())
    }
}

impl<'a> SerializeTuple for &'a mut Resp3Serializer {
    type Ok = ();

    type Error = RedisError;

    fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: ?Sized + serde::Serialize,
    {
        value.serialize(&mut **self)
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        Ok(())
    }
}

impl<'a> SerializeTupleStruct for &'a mut Resp3Serializer {
    type Ok = ();

    type Error = RedisError;

    fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: ?Sized + serde::Serialize,
    {
        value.serialize(&mut **self)
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        Ok(())
    }
}

impl<'a> SerializeTupleVariant for &'a mut Resp3Serializer {
    type Ok = ();

    type Error = RedisError;

    fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: ?Sized + serde::Serialize,
    {
        value.serialize(&mut **self)
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        Ok(())
    }
}

impl<'a> SerializeMap for &'a mut Resp3Serializer {
    type Ok = ();
    type Error = RedisError;

    fn serialize_key<T>(&mut self, key: &T) -> Result<(), Self::Error>
    where
        T: ?Sized + serde::Serialize,
    {
        key.serialize(&mut **self)
    }

    fn serialize_value<T>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: ?Sized + serde::Serialize,
    {
        value.serialize(&mut **self)
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        Ok(())
    }
}

impl<'a> SerializeStruct for &'a mut Resp3Serializer {
    type Ok = ();

    type Error = RedisError;

    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
    where
        T: ?Sized + serde::Serialize,
    {
        key.serialize(&mut **self)?;
        value.serialize(&mut **self)
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        Ok(())
    }
}

impl<'a> SerializeStructVariant for &'a mut Resp3Serializer {
    type Ok = ();

    type Error = RedisError;

    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
    where
        T: ?Sized + Serialize,
    {
        key.serialize(&mut **self)?;
        value.serialize(&mut **self)
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        Ok(())
    }
}
